<template>
  <view class="container">
    <!-- 加载中蒙层 -->
    <view v-if="loading" class="loading-mask">
      <view class="loading-content">
        <text class="loading-text">加载中...</text>
      </view>
    </view>

    <!-- 任务列表 -->
    <scroll-view
      :scroll-y="true"
      class="task-list"
      @refresh="onRefresh"
      :refresher-enabled="true"
      :refresher-triggered="refresherTriggered"
    >
      <view
        v-for="task in equipments"
        :key="task.equipmentId"
        class="task-card"
      >
        <!-- 并排布局 -->
        <view class="task-row">
          <!-- 左侧：设备名 + 状态 -->
          <view class="task-left">
            <text class="device-name">{{ deviceName(task) }}</text>
            <text class="status" :class="statusClass(task.inspectionStatus)">
              {{ statusText(task.inspectionStatus) }}
            </text>
          </view>

          <!-- 右侧：详细信息 -->
          <view class="task-right">
            <view class="info-item">
              <text class="label">设备ID:</text>
              <text>{{ task.equipmentId }}</text>
            </view>
            <view class="info-item">
              <text class="label">预约时间:</text>
              <text>{{ formatDateTime(task.detectionTime) }}</text>
            </view>
            <view class="info-item">
              <text class="label">卖家:</text>
              <text>{{ task.userName || '未知卖家' }}</text>
            </view>
            <view class="info-item">
              <text class="label">电话:</text>
              <text 
                class="clickable-phone" 
                @click="showContactModal(task)"
              >
                {{ formatPhone(task.phone) }}
              </text>
            </view>
            <view class="info-item">
              <text class="label">任务ID:</text>
              <text>{{ task.reportId || '待定' }}</text>
            </view>
            <view class="info-item">
              <text class="label">备注:</text>
              <text :class="{ 'empty': !task.remark }">{{ task.remark || '未写' }}</text>
            </view>
          </view>
        </view>

        <!-- 操作按钮 -->
        <view class="task-actions">
          <template v-if="task.inspectionStatus === 'pending_contact'">
            <!-- 联系卖家：弹出电话操作 -->
            <button
              size="mini"
              type="primary"
              :disabled="!canContactOrReschedule(task)"
              @click="showContactModal(task)"
            >
              联系卖家
            </button>

            <!-- 修改预约 -->
            <button
              size="mini"
              plain
              :disabled="!canContactOrReschedule(task)"
              @click="rescheduleTask(task)"
            >
              修改预约
            </button>
          </template>

          <!-- 其他状态... -->

<button
  v-else-if="task.inspectionStatus === 'pending_inspection'"
  size="mini"
  type="primary"
  :disabled="!canStartInspection(task)"
  @click="startInspection(task)"
>
  开始检测
</button>

<!-- 提示语 -->
<view 
  v-if="task.inspectionStatus === 'pending_inspection' && !canStartInspection(task)" 
  class="warning-tip"
>
  <text>
    {{ 
      task.detectionTime 
        ? `检测时间未到，需等到 ${formatDateTime(task.detectionTime)}` 
        : '尚未预约检测时间，无法开始'
    }}
  </text>
</view>

          <button
            v-else-if="task.inspectionStatus === 'inspecting'"
            size="mini"
            type="warn"
            @click="continueInspection(task)"
          >
            继续检测
          </button>

          <button
            v-else-if="task.inspectionStatus === 'pending_upload'"
            size="mini"
            type="primary"
            @click="uploadReport(task)"
          >
            上传报告
          </button>

          <button
            v-else-if="task.inspectionStatus === 'completed'"
            size="mini"
            plain
            @click="viewReport(task)"
          >
            查看报告
          </button>
        </view>

        <!-- 权限提示 -->
        <view 
          v-if="task.inspectionStatus === 'pending_contact' && !canContactOrReschedule(task)" 
          class="warning-tip"
        >
          <text>暂无可检测订单，无法进行联系或预约操作</text>
        </view>
      </view>
    </scroll-view>

    <!-- 空数据 -->
    <view v-if="!loading && equipments.length === 0" class="empty-tip">
      <text>暂无检测任务</text>
    </view>
    <!-- 隐藏的 canvas，用于绘图 -->
<canvas 
  canvas-id="hiddenCanvas" 
  :style="{ position: 'absolute', left: '-9999px', width: '750rpx', height: '1200rpx' }"
/>
  </view>
</template>

<script setup>
/**
 * @type {import('@/types/equipment').Equipment}
 */

import { onMounted, ref } from 'vue'
// 导入 Pinia Store 和工具函数
import { useInspectionStore } from '../../../stores/inspection/inspection'
import { formatDateTime } from '../../../utils/date'

const store = useInspectionStore()
const { equipments } = store
//导入服务
import { AddDetectionReport } from '../../../services/task'
// 加载状态
const loading = ref(false)
const refresherTriggered = ref(false)
//修改预约表单
const form = ref({
  date:'',
	equipmentId:0
})

// 页面加载时初始化任务
onMounted(() => {
  loadTasks()
})

// 加载任务列表
const loadTasks = async () => {
  loading.value = true
  try {
    await store.initEquipments()
  } catch (err) {
    console.error('加载失败:', err)
    uni.showToast({ title: '加载失败', icon: 'error' })
  } finally {
    loading.value = false
    if (refresherTriggered.value) refresherTriggered.value = false
  }
}

// 下拉刷新
const onRefresh = async () => {
  refresherTriggered.value = true
  await loadTasks()
}

// 构造设备名称
const deviceName = (task) => {
  return `${task.brand || ''} ${task.model || ''}`.trim() || '未知设备'
}

// 状态文本
const statusText = (status) => {
  return {
    pending_contact: '待联系卖家',
    pending_inspection: '待检测',
    inspecting: '检测中',
    pending_upload: '待上传报告',
    completed: '已完成'
  }[status] || '未知状态'
}

// 状态样式类
const statusClass = (status) => `status-${status}`

// 是否可以联系或修改预约（必须 orderId 存在且 orderStatus === 1）
const canContactOrReschedule = (task) => {
  return Boolean(task.orderId && task.orderStatus === 1)
}

// 格式化手机号：13800138000 → 138****1234
const formatPhone = (phone) => {
  if (!phone) return '无号码'
  const str = String(phone).trim()
  if (!/^1[3-9]\d{9}$/.test(str)) return '无效号码'
  return str.replace(/^(\d{3})\d{4}(\d{4})$/, '$1****$2')
}

// 弹出联系方式操作菜单
const showContactModal = (task) => {
  if (!canContactOrReschedule(task)) {
    uni.showToast({ title: '当前订单状态不可操作', icon: 'none' })
    return
  }

  const phone = task.phone
  const name = task.userName || '该卖家'

  if (!phone) {
    uni.showToast({ title: '卖家未留电话', icon: 'none' })
    return
  }

  // 弹出底部操作菜单
  uni.showActionSheet({
    itemList: ['📞 拨打 ' + phone, '📋 复制电话号码'],
    itemColor: '#007aff',
    success: (res) => {
      if (res.tapIndex === 0) {
        // 拨打电话
        uni.makePhoneCall({
          phoneNumber: phone,
          success: () => uni.showToast({ title: '已拨通', icon: 'success' }),
          fail: () => uni.showToast({ title: '拨号失败', icon: 'error' })
        })
      } else if (res.tapIndex === 1) {
        // 复制号码
        uni.setClipboardData({
          data: phone,
          success: () => uni.showToast({ title: '已复制', icon: 'none' })
        })
      }
    },
    fail: () => {
      // 用户取消
    }
  })
}

// 修改预约时间
const rescheduleTask = async(task) => {
  if (!canContactOrReschedule(task)) {
    uni.showToast({ title: '当前订单状态不可修改预约', icon: 'none' })
    return
  }

  uni.showModal({
    editable: true,
    placeholderText: '如：2025-04-06 15:00',
    success: async(res) => {
      if (res.confirm && res.content.trim()) {
        // store.rescheduleTask(task.reportId, res.content.trim())
         form.value.date=res.content.trim()
         form.value.equipmentId=task.equipmentId
        const data=await AddDetectionReport(form.value)
        if(data.code==20000){
         uni.showToast({ title: '预约已更新', icon: 'none' })
        }
        
      }
    }
  })
}
// 判断是否可以开始检测
const canStartInspection = (task) => {
  // 状态不对
  if (!task || task.inspectionStatus !== 'pending_inspection') return false
  
  // 没有预约时间
  if (!task.detectionTime) return false

  const now = new Date()
  const scheduledTime = new Date(task.detectionTime)

  // 时间格式错误
  if (isNaN(scheduledTime.getTime())) {
    console.warn('无效的 detectionTime:', task.detectionTime)
    return false
  }

  // 当前时间必须 >= 预约时间
  return now >= scheduledTime
}
// 开始检测
const startInspection = (task) => {
  uni.showModal({
    content: `确认开始检测【${deviceName(task)}】？`,
    success: (res) => {
      if (res.confirm) {
        // const initData = {
        //   items: {
        //     外观: { result: '', remark: '', media: [] },
        //     部件功能: { result: '', remark: '', media: [] },
        //     性能参数: { result: '', remark: '', media: [] }
        //   },
        //   updatedAt: new Date().toISOString()
        // }

        // store.saveInspectionData(task.reportId, initData)
        store.updateInspectionStatus(task.reportId, 'inspecting')

        uni.navigateTo({
          url: `/subpackages/tasksDetail/tasksDetail?reportId=${task.reportId}`
        })
      }
    }
  })
}

// 继续检测
const continueInspection = (task) => {
  uni.navigateTo({
          url: `/subpackages/tasksDetail/tasksDetail?reportId=${task.reportId}`
  })
}

// 上传报告
const uploadReport = (task) => {
  // uni.chooseImage({
  //   count: 3,
  //   success: (res) => {
  //     uni.showLoading({ title: '上传中...' })
  //     setTimeout(() => {
  //       uni.hideLoading()
  //       const url = `https://example.com/report/${task.reportId}`
  //       store.uploadReportSuccess(task.reportId, url)
  //       uni.showToast({ title: '上传成功', icon: 'success' })
  //     }, 1000)
  //   }
  // })
}

// 查看报告（纯文字版）
const viewReport = (task) => {
  if (!task) return

  const {
    brand,
    model,
    equipmentId,
    appearanceDetection,
    componentFunctionDetection,
    performanceParameterDetection,
    detectionConclusion
  } = task

  const deviceName = `${brand || ''} ${model || ''}`.trim() || '未知设备'

  // 检查关键字段是否完整
  const missingFields = []
  if (!appearanceDetection) missingFields.push('外观检测')
  if (!componentFunctionDetection) missingFields.push('部件功能检测')
  if (!performanceParameterDetection) missingFields.push('性能参数检测')
  if (!detectionConclusion) missingFields.push('综合结论')

  if (missingFields.length > 0) {
    uni.showToast({ title: '数据不全', icon: 'none' })
    uni.showModal({
      title: '提示',
      content: `以下项目尚未填写：\n${missingFields.join('、')}\n请先完成检测后再查看报告。`,
      showCancel: false
    })
    return
  }

  // ✅ 生成结构化文字报告
  const reportText = `
【设备检测报告】

设备名称：${deviceName}
设备ID：${equipmentId}
检测时间：${formatDateTime(new Date())}

──────────────────────
一、外观检测
${appearanceDetection}

二、部件功能检测
${componentFunctionDetection}

三、性能参数检测
${performanceParameterDetection}

──────────────────────
综合结论
${detectionConclusion}
──────────────────────
本报告由系统根据业务员填写内容自动生成。
`.trim()

  // 弹出模态框显示报告
  uni.showModal({
    title: '检测报告详情',
    content: reportText,
    showCancel: true,
    cancelText: '关闭',
    confirmText: '复制内容',
    success: (res) => {
      if (res.confirm) {
        // 用户点击“复制内容”
        uni.setClipboardData({
          data: reportText,
          success: () => {
            uni.showToast({ title: '已复制到剪贴板', icon: 'none' })
          },
          fail: () => {
            uni.showToast({ title: '复制失败', icon: 'error' })
          }
        })
      }
    }
  })
}

</script>

<style>
.container {
  padding: 20rpx;
  background-color: #f8f8f8;
  min-height: 100vh;
}

.task-list {
  height: 100vh;
}

/* 加载蒙层 */
.loading-mask {
  position: fixed; top: 0; left: 0; right: 0; bottom: 0;
  background-color: rgba(0,0,0,.4); display: flex; justify-content: center; align-items: center; z-index: 999;
}
.loading-content {
  background: #fff; padding: 40rpx 60rpx; border-radius: 16rpx;
}
.loading-text {
  font-size: 32rpx; color: #333;
}

/* 卡片 */
.task-card {
  background-color: #ffffff;
  border-radius: 16rpx;
  padding: 24rpx;
  margin-bottom: 20rpx;
  box-shadow: 0 2rpx 10rpx rgba(0,0,0,.1);
}

/* 并排布局 */
.task-row {
  display: flex;
  gap: 20rpx;
  margin-bottom: 16rpx;
}

.task-left {
  flex: 1;
  min-width: 180rpx;
}

.device-name {
  font-size: 32rpx;
  font-weight: bold;
  color: #333;
  display: block;
  margin-bottom: 8rpx;
}

.status {
  font-size: 24rpx;
  padding: 4rpx 12rpx;
  border-radius: 8rpx;
}

.status-pending_contact { background-color: #fff3cd; color: #856404; }
.status-pending_inspection { background-color: #d1ecf1; color: #0c5460; }
.status-inspecting { background-color: #f8d7da; color: #721c24; }
.status-pending_upload { background-color: #fff3cd; color: #856404; }
.status-completed { background-color: #d4edda; color: #155724; }

/* 右侧详情 */
.task-right {
  flex: 2;
  font-size: 28rpx;
  color: #666;
}

.info-item {
  display: flex;
  margin-bottom: 6rpx;
}

.info-item .label {
  width: 140rpx;
  color: #999;
  font-weight: normal;
}

.clickable-phone {
  color: #007aff;
  text-decoration: underline;
  font-size: 28rpx;
}

.empty {
  color: #aaa;
  font-style: italic;
}

/* 操作按钮 */
.task-actions {
  display: flex;
  flex-wrap: wrap;
  gap: 12rpx;
  margin-top: 12rpx;
}

.warning-tip {
  font-size: 24rpx;
  color: #999;
  margin-top: 8rpx;
  text-align: center;
}

.empty-tip {
  text-align: center;
  color: #999;
  margin-top: 100rpx;
}
</style>